//
//  LevelScene.m
//  lianliankan
//
//

#import "LevelScene.h"
#import "GameMenu.h"
#import "PlayScene.h"
#import "DB.h"

@implementation LevelScene

// 初始化场景
- (id) init
{
	if((self = [super init]))
	{

		// 屏幕尺寸
		CGSize screenSize = [[CCDirector sharedDirector] winSize];
		
		// 背景图片
		CCSprite *bg = [CCSprite spriteWithFile:@"background.png"];
		bg.position = ccp(screenSize.width / 2, screenSize.height / 2);
		[self addChild:bg z:-1 tag:1];
		
		// 标题
		CCLabelTTF *sceneTitle = [CCLabelTTF labelWithString:@"连连看" fontName:@"Marker Felt" fontSize:32];
		sceneTitle.position = ccp(screenSize.width /2 , screenSize.height - 60);
		[self addChild:sceneTitle z:0 tag:2];
        
		// 关卡总数
		NSInteger levelTotal = [DB fetchGameLevelTotal];
        
		// 已解锁关卡
		NSInteger levelUnlockNum = [[DB fetchUser] gameLevelId];
        if (levelUnlockNum < 1) 
        {
            levelUnlockNum = 1;
        }
        
		// 缓存图片
		CCSpriteBatchNode *LevelLockedBatch = [CCSpriteBatchNode batchNodeWithFile:@"levellocked.png"];
		[self addChild:LevelLockedBatch];
		
		// 行
		int row = 1;
		// 例
		int col = 1;

		
		CCMenu *mn = [CCMenu menuWithItems:nil];
		
		for (int i = 0; i < levelTotal; ++i) 
		{
			// 每行只显示 kRowDisplayLevelNum 个关卡
			if ((i % kRowDisplayLevelNum) == 0) 
			{
				col = 1;
				row++;
			}
			
			// 偏移系数
			float offsetPraction = ((float)(col)) / (kRowDisplayLevelNum + 1);
			// X轴坐标
			float positionX = screenSize.width * offsetPraction;
			// Y轴坐标
			float positionY = screenSize.height - (66 * row);
			
			// 已解锁关卡
			if (i < levelUnlockNum)
			{
				// 已解锁关卡按钮
				CCMenuItem *levelUnlock = [CCMenuItemImage 
										   itemFromNormalImage:@"level.png" 
										   selectedImage:@"levelselected.png" 
										   target:self
										   selector:@selector(selectLevel:)];
				
				levelUnlock.position = ccp(positionX, positionY);
				[mn addChild:levelUnlock z:1 tag:i];
				
				// 关卡数
				CCLabelTTF *levelNumber = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%i", i + 1] fontName:@"Marker Felt" fontSize:14];
				levelNumber.position = ccp(16, 16);
				levelNumber.color = ccc3(116, 170, 45);
				[levelUnlock addChild:levelNumber z:1];
            }
            else
            {
                CCSprite *levelLockedSprite = [CCSprite spriteWithFile:@"levellocked.png"];
                levelLockedSprite.position = ccp(positionX, positionY);
                [LevelLockedBatch addChild:levelLockedSprite];
            }
            
			col++;
		}
        
		mn.position = ccp(0, 0);
		[self addChild:mn]; 
        
	}
	return self;
}

// 选择关卡
- (void) selectLevel : (id) sender
{
	NSInteger level = [sender tag] + 1;
	CCLOG(@"%d", level);
    
    [PlayScene gotoLevel: level];
	
	CCScene *sc = [CCScene node];
	[sc addChild:[PlayScene node]];
	
	[[CCDirector sharedDirector] replaceScene:sc];
}

// 释放资源
- (void) dealloc
{
	CCLOG(@"%@:%@", NSStringFromSelector(_cmd), self);
	[super dealloc];
}

@end
